package de.urlaub.server.comm;

import java.util.Hashtable;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.interceptor.Interceptors;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

import de.urlaub.client.data.Employee;
import de.urlaub.server.logging.LoggingInterceptor;

@Stateless
@Interceptors(LoggingInterceptor.class)
public class HornetQSender implements HornetQSenderRemote 
{			
	@Override
	public void sendMessage(Employee employee, String messageText)
	{
		try
		{
			// Step 1. Create an initial context to perform the JNDI lookup.
			Hashtable<String, String> env = new Hashtable<String, String>();
			env.put(Context.PROVIDER_URL, "jnp://localhost:1099");
			env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
			env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
			Context ctx = new InitialContext(env);
	
			// Step 2. Lookup the connection factory
			ConnectionFactory cf = (ConnectionFactory)ctx.lookup("/ConnectionFactory");
	
			// Step 3. Lookup the JMS queue
			Queue queue = (Queue)ctx.lookup("/queue/DLQ");
	
			// Step 4. Create the JMS objects to connect to the server and manage a session
			Connection connection = cf.createConnection();
			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
	
			// Step 5. Create a JMS Message Producer to send a message on the queue
			MessageProducer producer = session.createProducer(queue);
	
			// Step 6. Create a Message and send it using the producer
			TextMessage textMessage = session.createTextMessage();
			textMessage.setText(employee.getEmployeeId() + ";" + messageText);
			producer.send(textMessage);
	
			// Finally, we clean up all the JMS resources
			connection.close();
		}
		catch (Exception e)
		{
			
		}
	}
}
